<?php
if (!defined("APP_PATH")) {
    define('APP_PATH', __DIR__ . '/../application/');
    // 加载框架引导文件
    require __DIR__ . '/../thinkphp/start.php';
}

use app\common\library\tron\Provider\HttpProvider;
use app\common\library\tron\Tron;
use think\Db;
use think\Exception;
use think\Log;
use fast\Http;

set_time_limit(0);
get_order_result();


function get_order_result()
{
    $redis = rds();
    $tron = null;

    $config = Config('transaction');
    $fullNode = new HttpProvider($config['fullNode_url']);
    $solidityNode = new HttpProvider($config['solidityNode_url']);
    $eventServer = new HttpProvider($config['eventServer_url']);
    try {
        $tron = new Tron($fullNode, $solidityNode, $eventServer);
    } catch (\Exception $e) {
        Log::error($e->getMessage());
    }

    while (true) {

        $time = time();
        $send = false;
        $oid = 0;
        try {
            $time_run = time() - $time;
            if ($time_run > 3600 * 2) { //如果超过2小时退出
                break;
            }
            $oid = $redis->rPop("withdraw_list");

            if ($oid) {
                Log::info("withdraw:" . $oid);
                $order = \db('tron_order')->where('id', $oid)->find();
                if (empty($order)) {
                    Log::error("找不到该订单");
                    continue;
                }

                if ($order['status'] != -1) {
                    Log::info("withdraw:" . $oid . "状态不对");
                    continue;
                }

                Log::info("withdraw:" . "找到订单");
                $quota = $order['amt'];
                $withdraw_address = $order['from_addr'];
                $tron->setPrivateKey($config['Private_key']);//设置私钥
                $response = $tron->sendTransaction($withdraw_address, $quota, null, $config['owner_address']);
                Log::info("withdraw:" . json_encode($response));
                $send = true;
                if (!empty($response['result'])) {
                    $txid = $response['txid'];
                    \db('tron_order')->where('id', $oid)->update(['txid' => $txid, 'status' => 0]);
                }
            } else {
                $user = \db('tron_order')->where('id', $oid)->find(); //查询用户表避免长时间没访问
                sleep(5);
            }
        } catch (\Exception $e) {
            Log::error("withdraw:" . $e->getFile() . "(" . $e->getCode() . ")" . $e->getLine() . $e->getMessage());
            if ($e->getCode() == "HY000") {
                if (!$send && $oid) {
                    $redis->lPush("withdraw_list", $oid);
                }
                break;
            }
        }

    }
}


